<?php

class Search_IndexController extends Zend_Controller_Action
{

    public function init()
    {
        Zend_Registry::get('layout')->setLayout('duty');
        
        $activeResource=Search_Model_Search::RESOURCE_NAME;
        
        // seting active resource
        Zend_Registry::set('resource',$activeResource);

        $this->view->headTitle()->append(Zend_Registry::get('locale')->_('Search'));
        
        $this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $this->view->flash_messages = $this->_flashMessenger->getMessages();
    }

    public function indexAction()
    {
        if (!Zend_Registry::get('user')->canView())
        {
            return $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl());
        }
        
        $session=new Zend_Session_Namespace('search');
        
        $text=isset($session->query) ? $session->query : '';
        
        $results=array();
        
        $form=new Search_Form_Search($text);
        
        $search=new Search_Model_Search();
        
        $request=$this->getRequest();
        
        if ($request->isPost())
        {
            unset($session->query);
            
            if ($form->isValid($request->getPost()))
            {
                $query=$form->getValue('query');
                
                $results=$search->find($query);
                
                if (empty($results))
                {
                    $this->_helper->FlashMessenger(Zend_Registry::get('locale')->_('No documents found'));
                 //   return $this->_helper->redirector('index');
                    return $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl('search'));
                } else
                {
                    $session->query=$form->getValue('query');
                }
            }
        } elseif (!empty($text))
        {
            $results=$search->find((string) $text);
        }
        
        if (!empty($results))
        {
            $results=$search->fetch($results,(int) $this->_getParam('key'),10);
        }
        
        $this->view->form=$form;
        $this->view->results=$this->view->paginator=$results;
    }
}

